/*
 * Copyright 2011-2012 by The Regents of the University of California Licensed
 * under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. you may obtain a copy of the
 * License from
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package edu.ucsd.db.bassarisk.storage.loading;

import java.nio.ByteBuffer;

import edu.ucsd.db.bassarisk.data.values.LongType;
import edu.ucsd.db.bassarisk.storage.common.ColumnStore;

public class VariableLengthLongDrawerIndexer extends
    VariableLengthLongSegmentIndexer implements IDrawerIndexer<LongType> {
  private static final short drawerIndexVersion = 3;

  private final short LOCAL_HEADER_BYTES = 2;

  public VariableLengthLongDrawerIndexer() {
    super();
    this.reset();
  }

  @Override
  public boolean indexCard(final ColumnSegmentInfo<LongType> cardInfo,
                           final boolean canIncreaseIndexSize) {
    long firstEntryIndex = cardInfo.getFirstEntryIndex();
    long cardEntryCount = cardInfo.getEntryCount();

    if (!canIncreaseIndexSize) {
      // Then we should only proceed if there is defiantly enough room to index
      // another data card without adding another index card.

      // First, how many bytes do we need to index this card?
      int spaceRequired = this.longCodec.bytesRequired(cardEntryCount);
      if (this.numSegmentsIndexed == 0) {
        spaceRequired += this.longCodec.bytesRequired(firstEntryIndex);
      }

      // How much slack is there in the last index card?
      // The second modulo operator patches the corner case where the index
      // currently takes up a round number of cards.
      int slack =
          (ColumnStore.BYTES_IN_CARD - (this.bytesConsumed % ColumnStore.BYTES_IN_CARD))
              % ColumnStore.BYTES_IN_CARD;
      if (slack < spaceRequired) { return false; }
    }

    if (this.numSegmentsIndexed == 0) {
      this.bytesConsumed +=
          this.longCodec.encode(this.entryRangeIndexBuffer, firstEntryIndex);
    }
    this.bytesConsumed +=
        this.longCodec.encode(this.entryRangeIndexBuffer, cardEntryCount);

    this.entryCount += cardInfo.getEntryCount();
    this.numSegmentsIndexed++;
    return true;
  }

  @Override
  public void reset() {
    super.reset();
    this.bytesConsumed += this.LOCAL_HEADER_BYTES;
  }

  @Override
  public int writeIndex(final ByteBuffer drawer, final int startCardIndex) {
    int cardsRequired = this.cardsRequired();
    int lastCardIndex = startCardIndex + cardsRequired - 1;
    assert lastCardIndex < ColumnStore.CARDS_IN_DRAWER;

    this.writeCommonData(drawer, startCardIndex);

    int headerBytes = this.LOCAL_HEADER_BYTES + this.COMMON_HEADER_BYTES;
    int headerPositionBase = (lastCardIndex + 1) * ColumnStore.BYTES_IN_CARD;
    drawer.position(headerPositionBase - headerBytes);
    this.writeCommonHeaders(drawer);

    drawer.putShort(drawerIndexVersion);
    drawer.clear();

    return cardsRequired;
  }
}